package com.code2roc.fastboot.util;

import com.code2roc.fastboot.framework.util.CommonUtil;
import com.code2roc.fastboot.framework.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class FrameJarUtil {
    private static Logger log = LoggerFactory.getLogger(FrameJarUtil.class);

    public static void copyFrameStaticFile(String packageName, boolean clearDir) {
        // 获取包的名字 并进行替换
        String packageDirName = packageName.replace('.', '/');
        // 定义一个枚举的集合 并进行循环来处理这个目录下的things
        Enumeration<URL> dirs;
        try {
            dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
            // 循环迭代下去
            while (dirs.hasMoreElements()) {
                // 获取下一个元素
                URL url = dirs.nextElement();
                // 得到协议的名称
                String protocol = url.getProtocol();
                if ("jar".equals(protocol)) {
                    // 如果是jar包文件
                    // 定义一个JarFile
                    JarFile jar;
                    try {
                        // 获取jar
                        jar = ((JarURLConnection) url.openConnection()).getJarFile();
                        String templateDecompressPath = "tempfiles/decompress/" + CommonUtil.getNewGuid() + "/";
                        File targetFile = new File(templateDecompressPath);
                        if (!targetFile.exists()) {
                            targetFile.mkdirs();
                        }
                        decompressJarFile(jar, templateDecompressPath);
                        String frameStaticPath = templateDecompressPath + "public/";
                        File frameStaticFile = new File(frameStaticPath);
                        if (frameStaticFile.exists()) {
                            String copyTargetPath = "static/";
                            File copyTargetFolder = new File(copyTargetPath);
                            if (copyTargetFolder.exists() && clearDir) {
                                FileUtil.deleteFileFolder(copyTargetPath);
                            }
                            copyTargetFolder.mkdirs();
                            FileUtil.copyFileFolder(frameStaticPath, copyTargetPath);
                        }
                        FileUtil.deleteFileFolder(templateDecompressPath);
                        log.debug(packageName + "静态文件复制完毕！");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static synchronized void decompressJarFile(JarFile jf, String outputPath) {
        if (!outputPath.endsWith(File.separator)) {
            outputPath += File.separator;
        }
        File dir = new File(outputPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            for (Enumeration<JarEntry> e = jf.entries(); e.hasMoreElements(); ) {
                JarEntry je = (JarEntry) e.nextElement();
                String outFileName = outputPath + je.getName();
                File f = new File(outFileName);
                if (je.isDirectory()) {
                    if (!f.exists()) {
                        f.mkdirs();
                    }
                } else {
                    File pf = f.getParentFile();
                    if (!pf.exists()) {
                        pf.mkdirs();
                    }
                    InputStream in = jf.getInputStream(je);
                    OutputStream out = new BufferedOutputStream(
                            new FileOutputStream(f));
                    byte[] buffer = new byte[2048];
                    int nBytes = 0;
                    while ((nBytes = in.read(buffer)) > 0) {
                        out.write(buffer, 0, nBytes);
                    }
                    out.flush();
                    out.close();
                    in.close();
                }
            }
        } catch (Exception e) {
            log.debug("解压" + jf.getName() + "出错---" + e.getMessage());
        } finally {
            if (jf != null) {
                try {
                    jf.close();
                    File jar = new File(jf.getName());
                    if (jar.exists()) {
                        jar.delete();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
